// 创建服务器
const http = require("http");
const fs = require("fs");
var sever = http.createServer(function (request, response) {
  const html = "./index.html";

  // 获取文件状态
  fs.stat(html, function (err, stats) {
    if (err) {
      // 发送404响应
      response.writeHead(404);
      response.end("404 Not Found.");
    } else {
      // 发送200响应
      response.writeHead(200);
      // response是一个writeStream对象，fs读取html后，可以用pipe方法直接写入
      fs.createReadStream(html).pipe(response);
    }
  });
});

sever.listen(8080); //设置端口

console.log("服务已启动 http://127.0.0.1:8080");


//获取本地IP
function getLocalIP() {
  const os = require("os");
  const netInfo = os.networkInterfaces(); //网络信息
  let ip = "";
  for (let dev in netInfo) {
    //win7的网络信息中显示为本地连接，win10显示为以太网
    if (dev === "本地连接" || dev === "以太网") {
      for (let j = 0; j < netInfo[dev].length; j++) {
        if (netInfo[dev][j].family === "IPv4") {
          ip = netInfo[dev][j].address;
          break;
        }
      }
    }
  }
  return ip;
}

console.log(`区域网地址 http://${getLocalIP()}:8080`);
